﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MiniX.Manage.Data;
using MiniX.Models;
using MiniX.Utility.Helper;
using Senparc.CO2NET.Extensions;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace MiniX.Manage.Controllers
{

    /// <summary>
    /// 版权所有: Copyright © 2023 Cloudin. 保留所有权利。
    /// 内容摘要: SettingInfo 处理请求的类
    /// 创建日期：2023年5月20日
    /// 更新日期：2023年7月22日
    /// 版    本：V1.0.11 
    /// 作    者：Cloudin
    /// </summary>
    [Authorize]
    public class SettingInfoController : BaseController<SettingInfoController>
    {

        /// <summary>
        /// 配置信息 实例化数据上下文
        /// </summary>
        /// <param name="context"></param>
        public SettingInfoController(MiniXManageContext context) : base(context)
        {

        }

        /// <summary>
        /// 管理/列表页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 新增页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit()
        {
            return View();
        }

        /// <summary>
        /// 详情页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Views()
        {
            return View();
        }

        /// <summary>
        /// 获取配置信息列表数据
        /// </summary>
        /// <param name="parent_id">父目录ID</param>
        /// <returns>返回配置信息JSON数据集合</returns>
        public async Task<IActionResult> List(int parent_id)
        {
            try
            {
                if (parent_id == -1)
                {
                    var result = from item in _context.Set<SettingInfo>().Where(t => t.parent_id == -1 && t.is_manage_show)
                                 select new
                                 {
                                     item.setting_info_id,
                                     item.info_name,
                                     item.parent_id,
                                     item.sort_num,
                                     item.is_show,
                                     item.is_manage_show,
                                     item.type_id,
                                     type_name = item.type_id > 0 ? _context.mini_setting_types.FirstOrDefault(t => t.type_id == item.type_id)!.type_name : "-",
                                     item.info_value,
                                     item.info_content,
                                     show_info_content = CommonHelper.FormatContent(item.info_content, 100),
                                     item.info_path,
                                     show_info_path = !string.IsNullOrEmpty(item.info_path) ? GetSettingInfoValue((int)ENUMHelper.SettingInfoType.AliyunCallbackServer) + item.info_path : "/images/no_photo.png",
                                     item.is_open,
                                     item.ext_link,
                                     item.ext_desc,
                                     item.info_tips,
                                     item.info_remark,
                                     item.created_at,
                                     format_time = item.created_at.ToString("yyyy-MM-dd HH:mm"),
                                     haveChild = _context.mini_setting_info.Any(t => t.parent_id == item.setting_info_id)
                                 };

                    long lCount = result.LongCount();
                    var list = await result.OrderBy(t => t.sort_num).ToListAsync();
                    AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.List + "" + (int)ENUMHelper.InfoType.Info, "查询文章分类LINQ=" + result.Expression.ToString() + ",DATA=" + list.ToJson());

                    return Json(new { code = 0, msg = "success", data = list, count = lCount });
                }
                else
                {
                    var result = from item in _context.Set<SettingInfo>().Where(t => t.parent_id == parent_id && t.is_manage_show)
                                 select new
                                 {
                                     item.setting_info_id,
                                     item.info_name,
                                     item.parent_id,
                                     item.sort_num,
                                     item.is_show,
                                     item.is_manage_show,
                                     item.type_id,
                                     type_name = item.type_id > 0 ? _context.mini_setting_types.FirstOrDefault(t => t.type_id == item.type_id)!.type_name : "-",
                                     item.info_value,
                                     item.info_content,
                                     show_info_content = CommonHelper.FormatContent(item.info_content, 100),
                                     item.info_path,
                                     show_info_path = !string.IsNullOrEmpty(item.info_path) ? GetSettingInfoValue((int)ENUMHelper.SettingInfoType.AliyunCallbackServer) + item.info_path : "/images/no_photo.png",
                                     item.is_open,
                                     item.ext_link,
                                     item.ext_desc,
                                     item.info_tips,
                                     item.info_remark,
                                     item.created_at,
                                     format_time = item.created_at.ToString("yyyy-MM-dd HH:mm"),
                                     haveChild = _context.mini_setting_info.Any(t => t.parent_id == item.setting_info_id)
                                 };

                    long lCount = result.LongCount();
                    var list = await result.OrderBy(t => t.sort_num).ToListAsync();
                    AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.List + "" + (int)ENUMHelper.InfoType.Info, "查询文章分类LINQ=" + result.Expression.ToString() + ",DATA=" + list.ToJson());

                    return Json(new { code = 0, msg = "success", data = list, count = lCount });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> List");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.List, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 获取配置信息数据
        /// </summary>
        /// <returns>返回配置信息JSON数据集合</returns>
        public async Task<IActionResult> Select()
        {
            try
            {
                var list = await _context.mini_setting_info.OrderBy(t => t.setting_info_id).ToListAsync();
                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Select + "" + (int)ENUMHelper.InfoType.Info, "查询配置信息下拉填充,DATA=" + list.ToJson());

                return Json(new { code = 0, msg = "success", data = list });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Select");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Select, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取配置信息详情
        /// </summary>
        /// <param name="id">配置信息ID</param>
        /// <returns>返回单条配置信息JSON数据</returns>
        [HttpGet("/settinginfo/details")]
        public async Task<IActionResult> Details(int id)
        {
            try
            {
                log.Information("id=" + id);
                var result = await _context.mini_setting_info.Where(t => t.setting_info_id == id).Select(item => (new
                {
                    item.setting_info_id,
                    item.info_name,
                    item.parent_id,
                    item.sort_num,
                    item.is_show,
                    item.is_manage_show,
                    item.type_id,
                    type_name = item.type_id > 0 ? _context.mini_setting_types.FirstOrDefault(t => t.type_id == item.type_id)!.type_name : "-",
                    item.info_value,
                    item.info_content,
                    item.info_path,
                    show_info_path = !string.IsNullOrEmpty(item.info_path) ? GetSettingInfoValue((int)ENUMHelper.SettingInfoType.AliyunCallbackServer) + item.info_path : "/images/no_photo.png",
                    item.is_open,
                    item.ext_link,
                    item.ext_desc,
                    item.info_tips,
                    item.info_remark,
                    item.created_at,
                    format_time = item.created_at.ToString("yyyy-MM-dd HH:mm")
                })).FirstOrDefaultAsync();
                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Details + "" + (int)ENUMHelper.InfoType.Info, "获取配置信息详情ID=" + id + ",result=" + result.ToJson());
                if (result == null)
                {
                    return Json(new { code = 0, msg = "数据为空", count = 0 });
                }
                else
                {
                    return Json(new { code = 0, msg = "success", data = result });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Details");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Details, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 新增配置信息数据
        /// </summary>
        /// <param name="settingInfo">SettingInfo对象</param>
        /// <returns>返回新增配置信息后的单条JSON数据</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(SettingInfo settingInfo)
        {
            try
            {
                log.Information("settingInfo=" + settingInfo.ToJson());

                settingInfo.is_manage_show = true;
                settingInfo.created_at = DateTime.Now;
                if (!_context.mini_setting_info.Any(t => t.info_name!.Equals(settingInfo.info_name)))
                {
                    _context.mini_setting_info.Add(settingInfo);
                    await _context.SaveChangesAsync();
                    AddLogs((int)ENUMHelper.LogType.Create, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Create + "" + (int)ENUMHelper.InfoType.Info, "新增配置信息,settingInfo=" + settingInfo.ToJson());

                    return Json(new { code = 0, msg = "添加成功", data = settingInfo });
                }
                else
                {
                    return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = "添加失败，请不要重复添加！" });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Create");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID更改配置信息数据
        /// </summary>
        /// <param name="id">配置信息ID</param>
        /// <param name="settingInfo">SettingInfo对象</param>
        /// <returns>返回修改配置信息后的单条JSON数据</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, SettingInfo settingInfo)
        {
            try
            {
                log.Information("settingInfo=" + settingInfo.ToJson());
                var item = _context.mini_setting_info.Find(id);
                if (item != null)
                {
                    item.info_name = settingInfo.info_name;
                    item.sort_num = settingInfo.sort_num;
                    item.info_value = settingInfo.info_value;
                    item.info_content = settingInfo.info_content;
                    item.info_path = settingInfo.info_path;
                    item.ext_link = settingInfo.ext_link;
                    item.ext_desc = settingInfo.ext_desc;
                    // item.info_tips = settingInfo.info_tips;
                    item.is_open = settingInfo.is_open;
                    _context.mini_setting_info.Update(item);
                    await _context.SaveChangesAsync();
                    AddLogs((int)ENUMHelper.LogType.Update, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Edit + "" + (int)ENUMHelper.InfoType.Info, "编辑配置信息ID=" + id + ",settingInfo=" + settingInfo.ToJson());
                    return Json(new { code = 0, msg = "更新成功", data = item });
                }
                else
                {
                    return Json(new { code = 0, msg = "操作失败，ID=" + id + "不存在！" });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Edit");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Edit, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID更改排序
        /// </summary>
        /// <param name="id">分类ID</param>
        /// <param name="sort_num">排序</param>
        /// <returns>返回修改分类后的单条JSON数据</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SetSort(int id, int sort)
        {
            try
            {
                log.Information("id=" + id + "sort=" + sort);
                var item = _context.mini_setting_info.Find(id);
                if (item != null)
                {
                    item.sort_num = sort;
                    _context.mini_setting_info.Update(item);
                    await _context.SaveChangesAsync();
                    AddLogs((int)ENUMHelper.LogType.Delete, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Logout + "" + (int)ENUMHelper.InfoType.Info, "删除文章分类ID=" + id + ",sort=" + sort);

                    return Json(new { code = 0, msg = "更新成功", data = item });
                }
                else
                {
                    return Json(new { code = 0, msg = "操作失败，ID=" + id + "不存在！" });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> SetShow");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Set, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 更新状态状态
        /// </summary>
        /// <param name="id">配置信息ID</param>
        /// <param name="status">状态</param>
        /// <returns>返回更新状态后的单条JSON数据</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SetShow(long id, bool status)
        {
            try
            {
                log.Information("id=" + id + ",status=" + status);
                var item = await _context.mini_setting_info.FirstOrDefaultAsync(t => t.setting_info_id == id);
                if (item != null)
                {
                    item.is_show = status;
                    _context.mini_setting_info.Update(item);
                    await _context.SaveChangesAsync();
                    AddLogs((int)ENUMHelper.LogType.Update, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Edit + "" + (int)ENUMHelper.InfoType.Info, "更新配置信息ID=" + id);
                    return Json(new { code = 0, msg = "更新成功", data = item });
                }
                else
                {
                    return Json(new { code = 0, msg = "操作失败，ID=" + id + "不存在！" });
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> SetShow");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Edit, errmsg = ex.Message });
            }
        }


        /// <summary>
        /// 根据ID删除配置信息数据
        /// </summary>
        /// <param name="id">配置信息ID</param>
        /// <returns>返回删除操作信息</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                log.Information("id=" + id);
                var item = _context.mini_setting_info.Find(id);
                if (item == null)
                {
                    return Json(new { code = 0, msg = "操作失败，ID=" + id + "不存在！" });
                }
                _context.mini_setting_info.Remove(item);
                await _context.SaveChangesAsync();
                AddLogs((int)ENUMHelper.LogType.Delete, (int)ENUMHelper.Platform.Admin + "" + (int)ENUMHelper.OperateType.Logout + "" + (int)ENUMHelper.InfoType.Info, "删除配置信息ID=" + id + ",item=" + item.ToJson());

                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Delete");
                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Delete, errmsg = ex.Message });
            }
        }

    }
}
